package com.zpb.framework.handler;

import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson2.JSON;
import com.zpb.framework.domain.ApiResult;
import com.zpb.framework.domain.enums.ResultCodeEnum;
import com.zpb.framework.utils.ServletUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/11
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        ApiResult<Object> result = null;
        if (authException instanceof BadCredentialsException) {
            result= ApiResult.failure(ResultCodeEnum.ERROR_USERNAME_OR_PASSWORD);
        }else
        if(authException instanceof InsufficientAuthenticationException) {
            result = ApiResult.failure(ResultCodeEnum.USER_NO_LOGIN);
        }else{
            result = ApiResult.failure(ResultCodeEnum.UNKNOWN_ERROR.getCode(),authException.getMessage());
        }

        String jsonResult = JSON.toJSONString(result);
        ServletUtil.renderString(response, jsonResult);
    }
}
